<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :align-center="true"
    width="60%"
    style="padding: 0 30px"
    :title="`${dialogData.title}零工信息`"
  >
    <el-form
      ref="jobFormRef"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="120px"
      label-suffix=" :"
    >
      <el-form-item label="职位类别" prop="jobTypeId">
        <el-tree-select
          v-model="dialogData.itemInfo.typeId"
          :data="dialogData.jobTypes"
          :render-after-expand="false"
          placeholder="请选择职位类别"
          style="width: 100%"
          size="large"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="职位名称" prop="title">
        <el-input size="large" placeholder="请输入职位名称" v-model="dialogData.itemInfo.title" maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item label="联系人" prop="contactor">
        <el-input
          placeholder="请填写联系人"
          v-model="dialogData.itemInfo.contactor"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          placeholder="请填写联系人电话"
          v-model="dialogData.itemInfo.contactPhone"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="年龄">
        <el-select style="width: 100%" v-model="dialogData.itemInfo.age" class="m-2" placeholder="请选择工作年限" size="large">
          <el-option v-for="item in dialogData.dicts1" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-select style="width: 100%" v-model="dialogData.itemInfo.gender" class="m-2" placeholder="请选择工作年限" size="large">
          <el-option v-for="item in dialogData.dicts2" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="从业经验">
        <el-select
          style="width: 100%"
          v-model="dialogData.itemInfo.workAge"
          class="m-2"
          placeholder="请选择从业经验"
          size="large"
        >
          <el-option v-for="item in dialogData.dicts3" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="职位福利">
        <el-select
          size="large"
          style="width: 100%"
          v-model="dialogData.itemInfo.tags"
          multiple
          multiple-limit="3"
          placeholder="请选择福利"
        >
          <el-option v-for="item in dialogData.tags" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="其它福利">
        <div class="custom-wrapper">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            class="m-r-10"
            size="large"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            placeholder="请填写"
            ref="InputRef"
            v-model="inputValue"
            class="m-r-10"
            size="large"
            maxlength="4"
            show-word-limit
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="m-r-10" size="large" @click="showInput"> + 自定义福利 </el-button>
        </div>
      </el-form-item>
      <el-form-item label="工作时间">
        <el-date-picker
          v-model="dialogData.itemInfo.jobDate"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
          size="large"
        />
      </el-form-item>
      <el-form-item label="岗位费用">
        <el-col :span="12">
          <el-input-number
            style="width: 100%"
            v-model="dialogData.itemInfo.priceAmt"
            :min="1"
            :precision="2"
            :max="10000000"
            @change="handleChange"
            size="large"
          />
        </el-col>
        <el-col :span="12">
          <el-checkbox
            class="m-l-10"
            v-model="dialogData.itemInfo.flagTalk"
            label="可议价"
            true-value="Y"
            false-value="N"
            size="large"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="职位描述" style="align-items: flex-start">
        <WangEditor height="200px" v-model:value="dialogData.itemInfo.content" />
      </el-form-item>
      <el-form-item label="工作地址">
        <el-input v-model="dialogData.address" size="large" placeholder="请选择工作地址">
          <template #append>
            <el-button @click="openWorkAddress" :icon="AddLocation">标注位置</el-button>
          </template>
        </el-input>
        <div class="alert-box">
          <el-alert  show-icon title="输入地址信息后，请点击右侧按钮 [ 标注位置 ] 在地图上确认位置." size="small" type="warning" :closable="false" />
        </div>
      </el-form-item>
      <el-form-item>
        <div class="map-dialog-wrapper">
          <div class="map-box-wrapper">
            <div id="mcontainer" class="map-box"></div>
            <!-- <div class="map-query-box"></div> -->
          </div>
        </div>
      </el-form-item>
      <el-form-item label="岗位照片/视频">
        <section class="form-s2" style="padding-top: 1rem">
          <section class="file-upload-box">
            <UploadImgs
              v-model:fileList="dialogData.fileList"
              :disabled="dialogData.isView"
              :file-size="3"
              width="160px"
              height="160px"
              :api="uploadImg"
            >
              <template #tip> 不超过 3M </template>
            </UploadImgs>
          </section>
        </section>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="btn-box">
        <div class="left-box">
          <el-button :icon="CopyDocument" size="large" type="primary" @click="handleCopyCurJob" >
            复制当前岗位为新岗位
          </el-button>
          <el-checkbox
            class="m-l-10"
            v-model="dialogData.isCopy"
            label="已复制"
            size="large"
          />
        </div>
        <div class="right-box">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button size="large" :icon="CirclePlus" type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">
            确认发布
          </el-button>
        </div>
      </div>
      <el-divider />
      <el-alert title="点击【复制当前岗位为新岗位】按钮，以当前岗位为模板创建一个相同的新的岗位.不会对原有岗位造成任何影响." type="info" :closable="false" />
    </template>
  </el-dialog>
  <!-- <Map ref="mapRef" @refresh-data="handleRefreshMapData" /> -->
  <JobProtocolDialog ref="ptlDialogRef" @agree-protocol="handleAgreeProtocol"/>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, shallowRef, watch } from "vue";
import { DialogParam } from "@/biz/interface/DialogType";
import { CommonTree } from "@/biz/interface";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { FlexjobEntity } from "@/biz/interface/jobType";
import WangEditor from "@/components/WangEditor/index.vue";
// import Map from "@/components/Map/index.vue";
import { AddLocation } from "@element-plus/icons-vue";
import { ElInput, ElMessage, FormInstance } from "element-plus";
import UploadImgs from "@/components/Upload/ImgMultiple.vue";
import { uploadImg } from "@/api/modules/upload";
import { CirclePlus, CopyDocument } from "@element-plus/icons-vue";
import {
  getFlexjobTypesTreeApi,
  getFlexjobDictionarysApi,
  getFlexjobTagsApi,
  saveFlexjobApi,
  getFlexjobInfoApi
} from "@/api/modules/cpyjob/flexjob";
import { getCurUserInfoApi } from "@/api/modules/sys/user";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getCoordFromAddress, getAddressFromCoord } from "@/api/modules/common/map";
import JobProtocolDialog from "./jobProtocolDialog.vue";
import { fa } from "element-plus/es/locale";

interface PostDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  // 是否点击了复制当前岗位的按钮 - 即为新建
  isCopy:boolean;
  // 图片
  fileList: [];
  // 查找的地址信息
  addressObject:{},
  //查找的地址坐标
  addressLnglat: {};
  // 岗位类型树
  jobTypes: CommonTree[];
  // *  职位福利
  tags?: [];
  dicts1?: [];
  dicts2?: [];
  dicts3?: [];
  // 这个是详情地址
  address: string;
  //当前的数据对象
  itemInfo: FlexjobEntity;
}
//弹出框的参数
const dialogVisible = ref(false);
const btnLoading = ref(false);
const loadProtocal = ref(false);

//当前表单数据在这里初始化
const dialogData = reactive<PostDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  isCopy: false,
  fileList: [],
  addressObject:{},
  addressLnglat: {},
  jobTypes: [],
  address:"",
  itemInfo: {
    // * 标题
    title: "",
    // * 类型
    jobTypeId: undefined,
    // * 岗位地址
    jobAddress: {},
    // *  职位福利
    tags: [],
    // *  图片
    imgs: [],
    // *  视频
    vdos: [],
    // * 上传的资源，把图片和视频先合在一起维护
    reses: []
  }
});

  //数据较验
  const rules = reactive({
    title: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }]
  });

const mapConfig = {
  key: "32e88e4ed5ea47ee273ea5c3bb8d7a4a",
  version: "2.0",
  plugins: ["AMap.DistrictSearch"]
};

const mapInitInfo = {
  viewMode: "2D",
  zoom: 12,
  center: [105.602725, 37.076636]
};

const map = shallowRef(null);
const amap = shallowRef(null);

const initMap = () => {
  AMapLoader.load(mapConfig)
    .then(AMap => {
      map.value = new AMap.Map("mcontainer", mapInitInfo);
      amap.value = AMap;
    })
    .catch(e => console.log(e));
};

const initItemInfo = async (): Promise<void> => {
  dialogData.fileList = [];
  dialogData.address = "";
  dialogData.itemInfo = {
    // * 标题
    title: "",
    flagTalk: "Y",
    obAddress: {}
  };

await getCurUserInfoApi({}).then(res=>{
  if(res && res.data ){
      dialogData.itemInfo.contactor = res.data.name;
      dialogData.itemInfo.contactPhone = res.data.phone;
    }
  })
};

//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getFlexjobInfoApi({ id });
    dialogData.itemInfo = data as unknown as FlexjobEntity;

    dialogData.itemInfo.contactor = dialogData.itemInfo.contactorName;

    // 这个是字典值都是配置的字符串
    dialogData.itemInfo.age = dialogData.itemInfo.age + "";
    dialogData.itemInfo.gender = dialogData.itemInfo.gender + "";
    dialogData.itemInfo.workAge = dialogData.itemInfo.workAge + "";

    // 处理显示地址的
    if (dialogData.itemInfo.jobAddress) {
      dialogData.address = dialogData.itemInfo.jobAddress.address;
      // 定位一下地图
      if(dialogData.itemInfo.jobAddress.posX){
        let coord = [dialogData.itemInfo.jobAddress.posX, dialogData.itemInfo.jobAddress.posY]
        map.value!.setCenter(coord);
      }
    }

    // 处理工作时间
    dialogData.itemInfo.jobDate = [];
    if (dialogData.itemInfo.startDate) {
      dialogData.itemInfo.jobDate[0] = dialogData.itemInfo.startDate;
    }
    if (dialogData.itemInfo.endDate) {
      dialogData.itemInfo.jobDate[1] = dialogData.itemInfo.endDate;
    }

    // 处理自定义标签
    if (dialogData.itemInfo.customTags) {
      dynamicTags.value = dialogData.itemInfo.customTags.split(",") || [];
    }

    // 处理图片和视频
    dialogData.fileList.length = 0;
    let imgIdx = 1;
    if (dialogData.itemInfo.imgs) {
      dialogData.itemInfo.imgs.forEach(img => {
        dialogData.fileList.push({ name: imgIdx, url: img });
        imgIdx = imgIdx + 1;
      });
    }
    if (dialogData.itemInfo.vdos) {
      dialogData.itemInfo.vdos.forEach(vdo => {
        dialogData.fileList.push({ name: imgIdx, url: vdo });
        imgIdx = imgIdx + 1;
      });
    }
  }
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

const markerDragEnd = (e: any) => {
  //根据点的拖动后得到的坐标，重新获取位置信息
  if (e.lnglat) {
    dialogData.addressLnglat = { lng: e.lnglat.lng, lat: e.lnglat.lat };
    getAddressFromCoord(e.lnglat)
      .then(address => address.json())
      .then((ares: any) => {
        // console.log("拖动后的位置:", ares);
        dialogData.addressObject = ares.regeocode;
        dialogData.address = ares.regeocode.formatted_address || "";
        // 标记位置 
        handleMapAddress();
      });
  }
};

// 地图上的点
let marker = shallowRef(null);
// 打开地图，标记地址
const openWorkAddress = () => {
  // console.log("打开地图，标记地址");
  // mapRef.value.acceptParams({ type: "flexjob" });
  if (dialogData.address) {
    //先移除点
    if (marker.value) {
      map.value!.remove(marker);
    }

    getCoordFromAddress(dialogData.address)
      .then(res => res.json())
      .then((res: any) => {
        if (res && res.geocodes) {
          console.log("查询结果1:", res);

          // let coord = res.geocodes[0].location.split(",").map((e: string) => parseFloat(e));
          // addressObject.value = { lng: coord[0], lat: coord[1] };

          // 通过坐标获取最匹配的地址信息
          getAddressFromCoord(res.geocodes[0].location)
            .then(address => address.json())
            .then((ares: any) => {
              // console.log("查询结果2:", ares);
              dialogData.addressObject = ares.regeocode;
              dialogData.address = ares.regeocode.formatted_address;

              // 在地图上标点 - 这边会有多个点。
              if(res.geocodes){
                // 目前只显示第一个匹配的位置 
                let geo  = res.geocodes[0];
                let coord = geo.location.split(",").map((e: string) => parseFloat(e));
                map.value!.setCenter(coord);
                if (coord) {
                  // console.log("查询结果3: 在地图上标点", coord);
                  dialogData.addressLnglat = { lng: coord[0], lat: coord[1] };

                  marker.value = new amap.value!.Marker({
                    position: new amap.value!.LngLat(coord[0], coord[1]),
                    title: geo.formatted_address,
                    draggable: true,
                    cursor: "move"
                  });

                  marker.value.on("dragend", markerDragEnd);
                  map.value!.add(marker.value);

                  //标记位置 
                  handleMapAddress();
                }
              }
          });
        } else {
          ElMessage.error("未查到,请更精确定位");
        }
      });
  }
};

// 处理选定的位置
const handleMapAddress = ()=>{
  if(dialogData.addressObject){
    dialogData.itemInfo.jobAddress = {
      provinceName: dialogData.addressObject.addressComponent.province,
      cityName: dialogData.addressObject.addressComponent.city,
      areaName: dialogData.addressObject.addressComponent.district,
      posX: dialogData.addressLnglat.lng,
      posY: dialogData.addressLnglat.lat
    };

    // 如果areaName 不是字符串的时候，设置为空 地图返回了一个空的数组，参数异常。
    if(dialogData.itemInfo.jobAddress){
      if( typeof dialogData.itemInfo.jobAddress.areaName !== 'string'){
        // 设置为空
        dialogData.itemInfo.jobAddress.areaName="";
      };
      if( typeof dialogData.itemInfo.jobAddress.cityName !== 'string'){
        // 设置为空
        dialogData.itemInfo.jobAddress.cityName="";
      };
    };

    // console.log("标记后的岗位地址：",  dialogData.itemInfo.jobAddress);
  }
}

// const mapRef = ref();
// const handleRefreshMapData = (val: any) => {
//   dialogData.itemInfo.jobAddress = {
//     provinceName: val.provinceName,
//     cityName: val.cityName,
//     areaName: val.areaName,
//     address: val.address,
//     posX: val.lng,
//     posY: val.lat
//   };
//   // 这个用于显示
//   // dialogData.address = val.address;
// };

const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (dynamicTags.value && dynamicTags.value.length > 1) {
      ElMessage.error({ message: `最多可添加2个自定义福利.` });
      return;
    }
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 清空当前的ID即可
const handleCopyCurJob = ()=>{
  dialogData.isCopy = true;
  dialogData.itemInfo.id = "";
  loadProtocal.value = false;
}

const handleAgreeProtocol = ()=>{
  loadProtocal.value = true;
}

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }

    try {

      // 如果没有打开过，则必须先打开 - 零工协议
      if(!loadProtocal.value){
        handleOpenProtocolDialog();
        return;
      }

      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        
        if(!dialogData.itemInfo.jobAddress){
          ElMessage.error({ message: `请在地图上标注工作地址所在的位置` });
          return;
        }

        dialogData.itemInfo.jobAddress.address = dialogData.address;
        if(!dialogData.itemInfo.jobAddress.address){
          ElMessage.error({ message: `岗位地址不能为空.` });
          return;
        }

        if(!dialogData.itemInfo.jobAddress.posX){
          ElMessage.error({ message: `请在地图上标注工作地址所在的位置` });
          return;
        }

        if (dialogData.fileList) {
          dialogData.itemInfo.reses = [];
          dialogData.fileList.forEach(file => {
            // console.log("每个文件, ", file, file.url);
            if (file && file.url) {
              dialogData.itemInfo.reses.push(file.url);
            }
          });
        }

        // 处理岗位发布时间
        // console.log("时间数据", dialogData.itemInfo.jobDate);
        dialogData.itemInfo.jobDate && (dialogData.itemInfo.startDate = dialogData.itemInfo.jobDate[0]);
        dialogData.itemInfo.jobDate && (dialogData.itemInfo.endDate = dialogData.itemInfo.jobDate[1]);
        // 这个不要删除， 保留可不用修改
        // delete dialogData.itemInfo.jobDate;

        // // 填充自定义标签
        dialogData.itemInfo.customTags = "";
        if (dynamicTags.value && dynamicTags.value.length > 0) {
          dialogData.itemInfo.customTags = dynamicTags.value.join(",");
        }

        //提交数据
        // console.log("提交的数据", dialogData.itemInfo, dynamicTags.value);
        let res = await saveFlexjobApi({
          ...dialogData.itemInfo
        });
        if (res.data) {
          ElMessage.success({ message: `${dialogData.title},保存成功！` });
          //刷新列表数据
          emits("refresh-list");
          dialogVisible.value = false;
        }else {
          ElMessage.error({ message: `${res.message}`});
        }
      }
    } catch (error) {
      console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

//初始化一些参数
onMounted(async () => {
  // 获取零工岗位相关的类型
  getFlexjobTypesTreeApi({}).then(res => {
    dialogData.jobTypes = res.data as unknown as CommonTree[];
  });
  // 获取零工岗位相关的标签
  getFlexjobTagsApi().then(res => {
    // console.log("接收到的岗位标签", res);
    dialogData.tags = res.data as unknown as [];
  });
  // 获取零工相关的数据字段
  await getFlexjobDictionarysApi().then(res => {
    // console.log("接收到的数据字典值", res);
    const { data } = res;
    if (data) {
      let ages = data.filter(item => item.colName == "age") || [];
      dialogData.dicts1 = ages.map(item => {
        return { value: item.configKey, label: item.configValue };
      });

      let genders = data.filter(item => item.colName == "gender") || [];
      dialogData.dicts2 = genders.map(item => {
        return { value: item.configKey, label: item.configValue };
      });

      let workags = data.filter(item => item.colName == "workAge") || [];
      dialogData.dicts3 = workags.map(item => {
        return { value: item.configKey, label: item.configValue };
      });
    }
  });
});

// 打开 支付
const ptlDialogRef = ref();
const handleOpenProtocolDialog = () => {
  // 参数只需要jobId 为 id
  let params = {
    optType: OptEnum.EDIT,
    rowData: { id:  dialogData.itemInfo.id }
  };
  ptlDialogRef.value.acceptParams(params);
};

watch(dialogVisible, n => {
  if (n) {
    initMap();
  }
});

//页面事件
const emits = defineEmits(["refresh-list"]);

defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
